
namespace cframework_coroutineutil
{
    using UnityEngine;
    using UnityEngine.UI;

    public class UGUIWaitOnClick : CustomYieldInstruction
    {
        UnityEngine.Events.UnityAction listener;
        Button button;
        bool clicked = false;
        public override bool keepWaiting
        {
            get
            {
                if(clicked)
                {
                    if (listener != null)
                    {
                        button.onClick.RemoveListener(listener);
                        listener = null;
                    }
                }

                return clicked == false;
            }
        }

        public UGUIWaitOnClick(Button btn)
        {
            button = btn;

            listener = () =>
            {
                clicked = true;
            };

            btn.onClick.AddListener(listener);
        }

        ~UGUIWaitOnClick()
        {
            Reset();
        }

        public override void Reset()
        {
            if (button != null && listener != null)
            {
                button.onClick.RemoveListener(listener);
                listener = null;
                button = null;
            }

            clicked = false;

            base.Reset();
        }
    }

    public static class CoroutineUtilUGUI
    {
        //public static IEnumerator WaitOnClick(this Button btn)
        //{
        //    var clicked = false;
        //    void b()
        //    {
        //        clicked = true; 
        //    }

        //    btn.onClick.AddListener(b);

        //    yield return new WaitUntil(() => clicked);
            
        //    btn.onClick.RemoveListener(b);


        //    //while (!clicked)
        //    //{
        //    //    yield return null;
        //    //}

        //    //var a = new WaitUntil(() => clicked);
        //    //a.keepWaiting;
        //}

        public static UGUIWaitOnClick WaitOnClick(this Button btn)
        {
            return new UGUIWaitOnClick(btn);
        }
    }
}